<!DOCTYPE html>
<html lang="zh-CN">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>房屋预约平台</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: white;
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
        }

        .header {
            text-align: center;
            color: #2c3e50;
            margin-bottom: 40px;
        }

        .header h1 {
            font-size: 32px;
            margin-bottom: 10px;
        }

        .header p {
            font-size: 18px;
            opacity: 0.7;
        }

        .rooms-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
            gap: 30px;
        }

        .room-card {
            background: #f8f9fa;
            border: 1px solid #e0e0e0;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        }

        .room-content {
            padding: 25px;
        }

        .room-title {
            font-size: 20px;
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 10px;
        }

        .room-location {
            color: #7f8c8d;
            margin-bottom: 15px;
            font-size: 14px;
        }

        .room-price {
            font-size: 24px;
            font-weight: 700;
            color: #e74c3c;
            margin-bottom: 20px;
        }

        .book-btn {
            width: 100%;
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            border: none;
            padding: 12px 20px;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: opacity 0.3s ease;
        }

        .book-btn:hover {
            opacity: 0.9;
        }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 1000;
        }

        .modal-content {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            padding: 30px;
            border-radius: 15px;
            width: 400px;
            max-width: 90%;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
        }

        .modal h2 {
            margin-bottom: 20px;
            color: #2c3e50;
            text-align: center;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: 500;
            color: #34495e;
        }

        .form-group input,
        .form-group textarea {
            width: 100%;
            padding: 12px;
            border: 2px solid #ecf0f1;
            border-radius: 8px;
            font-size: 14px;
            transition: border-color 0.3s ease;
        }

        .form-group input:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: #667eea;
        }

        .form-group textarea {
            resize: vertical;
            min-height: 80px;
        }

        .modal-buttons {
            display: flex;
            gap: 15px;
            justify-content: flex-end;
            margin-top: 25px;
        }

        .btn {
            padding: 12px 25px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: opacity 0.3s ease;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
        }

        .btn-secondary {
            background: #95a5a6;
            color: white;
        }

        .btn:hover {
            opacity: 0.9;
        }

        .success-modal .modal-content {
            text-align: center;
        }

        .success-icon {
            font-size: 48px;
            color: #27ae60;
            margin-bottom: 20px;
        }

        .loading {
            text-align: center;
            padding: 60px 20px;
            color: #7f8c8d;
            font-size: 18px;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #7f8c8d;
            font-size: 18px;
        }

        .error-message {
            background: #e74c3c;
            color: white;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            text-align: center;
        }
    </style>
    </head>
    <body>
    <div class="container">
        <div class="header">
            <h1>房屋预约平台</h1>
            <p>找到您心仪的房屋，预约看房</p>
        </div>
        
        <div id="roomsContainer">
            <div class="loading">加载房屋信息中...</div>
        </div>
    </div>

    <!-- 预约看房模态框 -->
    <div class="modal" id="bookingModal">
        <div class="modal-content">
            <h2 id="modalTitle">预约看房</h2>
            <div id="errorMessage" class="error-message" style="display: none;"></div>
            <form id="bookingForm">
                <div class="form-group">
                    <label for="userName">姓名 *</label>
                    <input type="text" id="userName" name="name" required>
                </div>
                <div class="form-group">
                    <label for="userPhone">电话 *</label>
                    <input type="tel" id="userPhone" name="phone" required>
                </div>
                <div class="form-group">
                    <label for="userMessage">留言</label>
                    <textarea id="userMessage" name="message" placeholder="请留下您的看房需求或其他备注..."></textarea>
                </div>
                <div class="modal-buttons">
                    <button type="button" class="btn btn-secondary" onclick="closeModal()">取消</button>
                    <button type="submit" class="btn btn-primary">确认预约</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 预约成功模态框 -->
    <div class="modal success-modal" id="successModal">
        <div class="modal-content">
            <div class="success-icon">✓</div>
            <h2>预约成功！</h2>
            <div id="successInfo"></div>
            <div class="modal-buttons">
                <button type="button" class="btn btn-primary" onclick="closeSuccessModal()">确定</button>
            </div>
        </div>
    </div>

    <script>
        const API_BASE_URL = 'http://snuc/user-api';
        
        let rooms = [];
        let currentRoomId = null;

        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadRooms();
        });

        // 加载房屋列表
        async function loadRooms() {
            try {
                const response = await fetch(`${API_BASE_URL}/rooms`);
                if (response.ok) {
                    rooms = await response.json();
                } else {
                    rooms = [];
                }
                renderRooms();
            } catch (error) {
                console.error('加载房屋列表失败:', error);
                rooms = [];
                renderRooms();
            }
        }

        // 渲染房屋列表
        function renderRooms() {
            const container = document.getElementById('roomsContainer');
            
            if (rooms.length === 0) {
                container.innerHTML = '<div class="empty-state">暂无房屋信息</div>';
                return;
            }

            const roomsGrid = document.createElement('div');
            roomsGrid.className = 'rooms-grid';
            
            roomsGrid.innerHTML = rooms.map(room => `
                <div class="room-card">
                    <div class="room-content">
                        <div class="room-title">${room.title}</div>
                        <div class="room-location">📍 ${room.location}</div>
                        <div class="room-price">¥${room.price}/月</div>
                        <button class="book-btn" onclick="openBookingModal(${room.id}, '${room.title}')">
                            预约看房
                        </button>
                    </div>
                </div>
            `).join('');

            container.innerHTML = '';
            container.appendChild(roomsGrid);
        }

        // 打开预约模态框
        function openBookingModal(roomId, roomTitle) {
            currentRoomId = roomId;
            document.getElementById('modalTitle').textContent = `预约看房 - ${roomTitle}`;
            document.getElementById('bookingForm').reset();
            document.getElementById('errorMessage').style.display = 'none';
            document.getElementById('bookingModal').style.display = 'block';
        }

        // 关闭预约模态框
        function closeModal() {
            document.getElementById('bookingModal').style.display = 'none';
            currentRoomId = null;
        }

        // 关闭成功模态框
        function closeSuccessModal() {
            document.getElementById('successModal').style.display = 'none';
        }

        // 提交预约表单
        document.getElementById('bookingForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            if (!currentRoomId) return;

            const formData = new FormData(this);
            const bookingData = {
                name: formData.get('name'),
                phone: formData.get('phone'),
                message: formData.get('message') || ''
            };

            try {
                const response = await fetch(`${API_BASE_URL}/rooms/${currentRoomId}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(bookingData)
                });

                if (response.ok) {
                    const result = await response.json();
                    showSuccessModal(result);
                    closeModal();
                } else {
                    const error = await response.json();
                    showError(error.detail || '预约失败，请稍后重试');
                }
            } catch (error) {
                console.error('预约失败:', error);
                showError('网络错误，请稍后重试');
            }
        });

        // 显示错误信息
        function showError(message) {
            const errorDiv = document.getElementById('errorMessage');
            errorDiv.textContent = message;
            errorDiv.style.display = 'block';
        }

        // 显示预约成功信息
        function showSuccessModal(result) {
            const successInfo = document.getElementById('successInfo');
            successInfo.innerHTML = `
                <p style="margin: 20px 0;"><strong>房屋：</strong>${result.room_title}</p>
                <p style="margin: 10px 0;"><strong>预约人：</strong>${result.booking_info.name}</p>
                <p style="margin: 10px 0;"><strong>联系电话：</strong>${result.booking_info.phone}</p>
                ${result.booking_info.message ? `<p style="margin: 10px 0;"><strong>留言：</strong>${result.booking_info.message}</p>` : ''}
                <div style="margin-top: 20px; padding: 15px; background: #f8f9fa; border-radius: 8px;">
                    <p style="margin: 5px 0;"><strong>中介联系方式：</strong></p>
                    <p style="margin: 5px 0;">电话：400-888-8888</p>
                    <p style="margin: 5px 0;">微信：house_agent_001</p>
                    <p style="margin: 5px 0; font-size: 14px; color: #666;">我们会在24小时内与您联系安排看房</p>
                </div>
            `;
            document.getElementById('successModal').style.display = 'block';
        }

        // 点击模态框外部关闭
        document.addEventListener('click', function(e) {
            if (e.target.classList.contains('modal')) {
                if (e.target.id === 'bookingModal') {
                    closeModal();
                } else if (e.target.id === 'successModal') {
                    closeSuccessModal();
                }
            }
        });
    </script>
    </body>
</html>